<template>
  <div class="container">
    <nav-bar title="购物车" :cartShow="false" />
    <!-- 产品 -->
    <div class="products">
      <div 
        class="item" 
        v-for="(item, index) in cartList" 
        :key="index"
        @click="goToProduct(item.Id)"
      >
        <div 
          class="check" 
          :class="{'checked': item.checked}"
          @click.stop="cartCheck(index)"
        >
          <i></i>
        </div>
        <img :src='item.ImgUrl' />
        <div class="dis">
          <h3>{{item.Name}}</h3>
          <div class="picked-del">
            <div class="picked">
              <span>{{item.Color}} {{item.Size}}</span>
              <!-- <span>M;星云蓝-4490</span> -->
              <!-- <i class="arrow"></i> -->
            </div>
            <div class="delete" @click.stop="deleteCartProduct(index)">
              <img src='../../assets/img/delete.png' />
            </div>
          </div>
          <!-- <div class="store">
            库存紧张
          </div> -->
          <div class="price-num">
            <div class="price">
              <i>¥</i>
              <span>{{item.Price}}</span>
            </div>
            <div class="num-area">
              <div class="reduce" @click.stop="reduce(index)"></div>
              <div class="num">{{item.Count}}</div>
              <div class="plus" @click.stop="plus(index)"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="total">
      <div 
        class="all" 
        :class="{'all-checked': cartAllChecked}" 
        @click="checkAll"
      >
        <i></i>
        全选
      </div>
      <div class="price">合计: ¥{{totalPrice}}</div>
      <div class="submit" @click="goToSubmit">去结算</div>
    </div>
  </div>
</template>

<script>
import NavBar from 'components/common/NavBar'
import { Toast } from 'vant'
import { 
  getCartProduct, 
  updateCartProduct, 
  deleteCartProduct 
} from '../../network/cart'
import { getProductSkuId } from '../../network/product'

export default {
  components: {
    NavBar,
  },
  data() {
    return {
      userKey: localStorage.getItem('userKey'),
      num: 1,
      cartList: [],
    }
  },
  computed: {
    cartAllChecked(){
      let allChecked = this.cartList.every(item => {
        return item.checked
      })
      return allChecked
    },
    totalPrice(){
      let totalPrice = 0
      this.cartList.map(item => {
        if(item.checked){
          totalPrice = (totalPrice * 100 + item.Price * 100 * item.Count)/100
        }
      })
      return totalPrice.toFixed(2)
    }
  },
  mounted(){
    this.getCartProduct()
  },
  methods: {
    // 获取购物车
    getCartProduct(){
      let requestData = {
        userkey: this.userKey,
        // includeSB: "0"
      }
      getCartProduct(requestData, list => {
        // 控制是否选中 初始化
        list = list.map( item => {
          item.checked = false
          return item
        })
        this.cartList = list
      })
    },
    // 更新购物车数量 减少
    reduce(index){
      this.updateCart(index, true)
    },
    // 更新购物车数量 增加
    async plus(index){
      let productId = this.cartList[index].Id
      let SkuId = this.cartList[index].SkuId
      let count = Number(this.cartList[index].Count)
      let stock = await this.getProductSkuStock(productId, SkuId)
      if(count < stock){
        this.updateCart(index, false)
      } else {
        Toast('商品库存不足')
      }
    },
    getProductSkuStock(productId, SkuId){
      return new Promise((resolve, reject) => {
        let requestData = {
          productId,
          colloPid: 0,
          userKey: this.userKey
        }
        getProductSkuId(requestData, skuInfo => {
          let item = skuInfo.filter(item => item.SkuId === SkuId)[0]
          resolve(item.Stock)
        })
      })
    },
    updateCart(index, isReduce){
      let product = this.cartList[index]
      let count = isReduce ? 
        Number(product.Count) - 1 : Number(product.Count) + 1
      let skuId = product.SkuId

      if(isReduce && count < 1){
        return false
      }

      // 发起请求 更新购物车商品数量
      let requestData = {
        userkey: this.userKey,
        jsonstr: `{"skus": [{ "skuId": "${skuId}","count": ${count}}]}`
      }
      updateCartProduct(requestData, () => {
        let count = Number(this.cartList[index].Count)
        if(isReduce && count>1){
          this.cartList[index].Count = count-1
        } else {
          this.cartList[index].Count = count+1
        }
      })
    },
    // 删除购物车
    deleteCartProduct(index){
      let product = this.cartList[index]
      let skuId = product.SkuId
      // 发起请求 删除购物车
      let requestData = {
        userkey: this.userKey,
        skuIds: skuId
      }
      deleteCartProduct(requestData, () => {
        this.cartList.splice(index, 1)
      })
    },
    cartCheck(index){
      let checked = this.cartList[index].checked
      this.$set(this.cartList[index], 'checked', !checked)
    },
    checkAll(){
      let flag = this.cartAllChecked
      this.cartList = this.cartList.map(item => {
        item.checked = !flag
        return item
      })
    },
    getProductList(){
      return new Promise(resolve => {
        let idx = 0
        let productList = []
        let cartItemIds = []
        let checkedNum = this.cartList.filter(item => item.checked).length
        this.cartList.map(async (item) => {
          let checkedStr = ''
          if(item.Color){
            checkedStr += item.Color
          }
          if(item.Size){
            checkedStr += item.Size
          }
          if(item.checked){
            let stock = await this.getProductSkuStock(item.Id, item.SkuId)
            if(stock < item.Count){
              Toast('商品库存不足')
              return false
            }
            productList.push({
              ProductName: item.Name,
              ProductPrice: item.Price,
              counts: item.Count,
              checked: checkedStr,
              imgUrl: item.ImgUrl
            })
            cartItemIds.push(item.CartItemId)
            idx++
          }
          if(idx>=checkedNum){
            resolve({productList, cartItemIds})
          }
        })
      })
    },
    // 结算
    async goToSubmit(){
      let obj = await this.getProductList()
      let productList = obj.productList
      let cartItemIds = obj.cartItemIds

      if(productList.length){
        // 缓存产品列表
        let requestData = {
          userkey: this.userKey,
          cartItemIds: cartItemIds.join(',')
        }
        localStorage.setItem('productRequestData', JSON.stringify(requestData))
        localStorage.setItem('productRequestList', JSON.stringify(productList))
        localStorage.setItem('productRequestAddress', null)
        this.$router.push({
          path: '/orderConfirm',
          query: {
            action: 0,
            shopId: this.cartList[0].ShopId,
          }
        })
      } else {
        Toast('请选择商品')
      }
    },
    goToProduct(id){
      this.$router.push({
        path: '/product',
        query: {
          id,
        }
      })
    },
  },
}
</script>

<style scoped>
.container{
  background-color: #ffffff;
}
.products{
  padding-bottom: 80px;
  border-top: 2px solid #f4f4f4;
}
.products .item{
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  margin-top: 30px;
  padding: 0 10px;
}
.products .item .check{
  flex-shrink: 0;
  padding: 38px 12px 0 8px;;
}
.products .item .check i{
  display: block;
  position: relative;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 1px solid #c4c4c4;
  box-sizing: border-box;
}
.products .item .checked i{
  border-color: #000000;
  background-color: #000;
}
.products .item .checked i:after{
  position: absolute;
  left: 5px;
  top: 1px;
  display: block;
  content: '';
  width: 4px;
  height: 8px;
  border-bottom: 2px solid #ffffff;
  border-right: 2px solid #ffffff;
  transform: rotate(45deg);
}
.products .item img{
  flex-shrink: 0;
  width: 100px;
  height: 100px;
  margin-right: 10px;
  border-radius: 3px;
}
.products .item .dis{
  flex-grow: 1;
  min-width: 100px;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.products .item .dis h3{
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}
.products .item .dis .picked-del{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0;
}
.products .item .dis .picked{
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 3px;
  color: #999999;
  display: inline-block;
  background: #f4f4f4;
}
.products .item .dis .picked .arrow{
  display: inline-block;
  width: 5px;
  height: 5px;
  border-right: 1px solid #999;
  border-bottom: 1px solid #999;
  transform: rotate(45deg);
  margin: 0 0 3px 8px;
}
.products .item .store{
  line-height: 2;
  font-size: 14px;
  color: #d50721;
}
.products .item .dis .price-num{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.products .item .dis .price{
  color: #d50721;
}
.products .item .dis .time{
  color: #999999;
}
.products .item .dis .price span{
  font-size: 16px;
  padding-left: 5px;
}
.products .item .dis .delete{
  width: 30px;
  height: 30px;
}
.products .item .dis .delete img{
  width: 70%;
  height: 70%;
  margin: 15%;
}
.products .item .dis .num-area{
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #e4e4e4;
  border-radius: 3px;
}
.products .item .dis .num-area .reduce,
.products .item .dis .num-area .plus{
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
}
.products .item .dis .num-area .num{
  width: 40px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-left: 1px solid #e4e4e4;
  border-right: 1px solid #e4e4e4;
}
.products .item .dis .num-area .reduce:before,
.products .item .dis .num-area .plus:before{
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -4px;
  content: '';
  display: block;
  width: 9px;
  height: 1px;
  background-color: #999999;
}
.products .item .dis .num-area .plus:after{
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -5px;
  content: '';
  display: block;
  width: 1px;
  height: 10px;
  background-color: #999999;
}
.total{
  display: flex;
  align-items: center;
  height: 60px;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  border-top: 1px solid #e7e7e7;
  background-color: #ffffff;
}
.total .all{
  flex-grow: 1;
  position: relative;
  padding-left: 50px;
}
.total .all i{
  display: block;
  content: '';
  position: absolute;
  left: 20px;
  top: 50%;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 1px solid #c4c4c4;
  flex-shrink: 0;
  margin-top: -9px;
  box-sizing: border-box;
}
.total .all-checked i{
  border-color: #000000;
  background-color: #000;
}
.total .all-checked i:after{
  position: absolute;
  left: 5px;
  top: 1px;
  display: block;
  content: '';
  width: 4px;
  height: 8px;
  border-bottom: 2px solid #ffffff;
  border-right: 2px solid #ffffff;
  transform: rotate(45deg);
}
.total .price{
  padding-right: 20px;
}
.total .submit{
  color: #ffffff;
  text-align: center;
  line-height: 60px;
  width: 100px;
  background-color: #000000;
}
</style>